package practice2;

import practice2.Node;

public class LinkedListQueue {
	private int num = 0;// 队列内元素个数
	private int maxSize;// 最大容量
	private Node headNode = new Node(0);// 创建头节点
	private Node tailNode = headNode;// 当前尾节点，一开始指向头节点

	public int getMaxSize() {
		return maxSize;
	}

	public void setMaxSize(int maxSize) {
		this.maxSize = maxSize;
	}

	public Node getHeadNode() {
		return headNode;
	}

	public void setHeadNode(Node headNode) {
		this.headNode = headNode;
	}

	public boolean isEmpty() {
		return num == 0;
	}

	public boolean isFull() {
		return num == maxSize;
	}

	// 向队列中添加元素
	public void offer(int value) {
		// 判断队列是否已满，若已满，就返回并提示
		if (isFull()) {
			System.out.println("队列已满！");
			return;
		}
		if (num == 0) {
			num++;
			Node newNode = new Node(value);// 创建一个新节点
			// 将新节点加入链表
			headNode = newNode;
			tailNode = newNode;
		} else {
			num++;
			Node newNode = new Node(value);// 创建一个新节点
			// 将新节点加入链表
			tailNode.setNext(newNode);
			newNode.setPreNode(tailNode);
			tailNode = newNode;
		}
	}

	public int poll() {
		// 判断队列是否为空
		if (isEmpty()) {
			throw new RuntimeException("队列为空！");
		}
		// 用pollValue保存头结点的元素值
		int pollValue = headNode.getValue();
		headNode = headNode.getNext();
		if (num == 1) {
			num--;// 队列元素个数减一
			return pollValue;
		}
		headNode.setPreNode(null);
		num--;// 队列元素个数减一
		return pollValue;
	}

	public void list() {
		if (isEmpty()) {
			System.out.println("队列为空！");
		}
		Node tempNode = headNode;
		int i = 0;
		while (i < num) {
			System.out.print(" " + tempNode.getValue());
			tempNode = tempNode.getNext();
			i++;
		}
		System.out.println("");
	}

}
